#/bin/bash -e
# should start in FABRIC_DEPLOY

source cluster_ip.conf

FABRIC_SDK_BRANCH="testWithCeph"

function down_redundancy() {
    cd $HOME/ceph_fabric_config/redundancy
    ./down_redundancy.sh
}

function redeploy_fabric() {
    # stop fabric-sdk for 4 orgs & start kafka containers
    for node in ${FABRIC_SDK_IP[@]}
    do
        ssh $node "
            source /etc/profile
            fabric_sdk=\$(ps -ef | grep main | grep -v grep | awk '{print \$2}')
            for id in \$fabric_sdk
            do
                sudo kill \$id
            done
            cd \$HOME/ceph_fabric_config/kafka
            git pull
            ./start.sh -i $node
        " &
    done
    wait
    # redeploy fabric
    ssh $FABRIC_DEPLOY "
        source /etc/profile
        cd \$HOME/ceph_fabric_config/fabric_deploy_splitted_1.4/
        ./deploy_fabric_peer_order.sh -b $FABRIC_SDK_BRANCH
    "
    # start fabric-sdk for 4 orgs
    for i in {0..3}
    do
        ssh ${FABRIC_SDK_IP[$i]} "
            source /etc/profile
            cd \$HOME/go/src/github.com/hyperledger/fabric-sdk/
            git pull
            git checkout testWithCeph
            git pull
            ./hosts_config.sh
            nohup go run main.go -o $i -b ${FABRIC_SDK_IP[$i]}:${KAFKA_PORT} -t ${KAFKA_TOPIC} > \$HOME/fabric_sdk.log 2>&1 &
        " &
    done
    wait
}

function restart_ceph() {
    for i in {0..3}
    do
        ssh ${CEPH_IP[$i]} "
            cd $HOME/ceph-demo/build
            ../src/stop.sh
            rm -rf out dev
            RGW=1 ../src/vstart.sh -c $i --smallmds --new -X --localhost --msgr1 --without-dashboard --fabric_kafka_brokers ${FABRIC_SDK_IP[$i]}:$KAFKA_PORT --fabric_kafka_topic ${KAFKA_TOPIC} --fabric_sdk_addr ${FABRIC_SDK_IP[$i]}:8080 --size_of_object_put_to_fabric 4194304 > \$HOME/ceph-demo/build/start.log 2>&1
        " &
    done
    wait
}

function test_ceph_health() {
    for node in ${CEPH_IP[@]}
    do
        ssh $node "
            ceph_status=\$(timeout 2s ceph health)
            if [ 0\$ceph_status == '0' ]; then
                exit -1
            fi
        "
        if [ $? -ne 0 ]; then
            echo "No ceph running in [$node], stop gen data"
            exit -1
        fi
    done
}

function gen_rados_objs() {
    for node in ${CEPH_IP[@]}
    do
        ssh $node "
            ceph osd pool create testbench 32 32
            ceph osd pool application enable testbench rgw
        " &
    done
    wait
    for node in ${CEPH_IP[@]}
    do
        ssh $node "
            rados --put-hash-to-fabric bench -p testbench 2 write -t 32 --no-cleanup >> \$HOME/ceph-demo/build/start.log
            # rados bench -p testbench 20 write -t 32 -b 4096 >> \$HOME/ceph-demo/build/start.log
        " &
    done
    wait
}

function deploy_redundancy() {
    cd $HOME/ceph_fabric_config/redundancy
    ./deploy_redundancy.sh
}


down_redundancy

redeploy_fabric

restart_ceph

test_ceph_health

gen_rados_objs

sleep 5s

deploy_redundancy